package ebj.common.redis.helper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

public class CSVUtil {
	/**
     * 导出
     * 
     * @param file csv文件(路径+文件名)，csv文件不存在会自动创建
     * @param dataList 数据
     * @return
     */
    public static boolean exportCsv(File file, List<String> dataList){
        boolean isSucess=false;
        
        FileOutputStream out=null;
        OutputStreamWriter osw=null;
        BufferedWriter bw=null;
        try {
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out);
            bw =new BufferedWriter(osw);
            if(dataList!=null && !dataList.isEmpty()){
                for(String data : dataList){
                    bw.append(data).append("\r");
                }
            }
            isSucess=true;
        } catch (Exception e) {
            isSucess=false;
        }finally{
            if(bw!=null){
                try {
                    bw.close();
                    bw=null;
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            }
            if(osw!=null){
                try {
                    osw.close();
                    osw=null;
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            }
            if(out!=null){
                try {
                    out.close();
                    out=null;
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            }
        }
        
        return isSucess;
    }
    
    /**
     * 导入
     * 
     * @param file csv文件(路径+文件)
     * @return
     */
    private static List<String> importCsv(File file){
        List<String> dataList=new ArrayList<String>();
        
        BufferedReader bufferedReader=null;
        try { 
            bufferedReader = new BufferedReader(new FileReader(file));
            String line = ""; 
            while ((line = bufferedReader.readLine()) != null) { 
                dataList.add(line);
            }
        }catch (Exception e) {
        }finally{
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                    bufferedReader=null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return dataList;
    }
    
    public static List<Map<String, String>> getKeyValPairsFromCSVFile(File file) {
    	List<Map<String, String>> keyValPairList = Lists.newArrayList();
    	
    	List<String> strings = importCsv(file);
		if (null != strings && strings.size() > 0) {
			for (String string : strings) {
				if (string.startsWith(",")) {
					string = string.substring(1, string.length()).replace("\"", "");
				}
				Map<String, String> keyValPair = Splitter.on(",").trimResults().withKeyValueSeparator(":").split(string);
				keyValPairList.add(keyValPair);
			}
			
		}
		return keyValPairList;
	}
    
    
    public static void main(String[] args) {
		String temp = ",\"mac_sha1\":\"ffc89c89b7614b488b93fcd1fa59bd6d517a4b36\",\"androidid\":\"81ee37eb202113b0\",\"mac_md5\":\"e4c4e425021ed0f7aeac17c7438145bb\"";
		System.out.println(temp + " | " + temp.length());
		if (temp.startsWith(",")) {
			temp = temp.substring(1, temp.length()).replace("\"", "");
		}
		System.out.println(temp + " | " + temp.length());
		Map<String, String> keyValPair = Splitter.on(",").trimResults().withKeyValueSeparator(":").split(temp);
		for (Entry<String, String> entry : keyValPair.entrySet()) {
			String key = entry.getKey();
			String val = entry.getValue();
			System.out.println(key + " - " + val);
		}
		
		System.out.println("////////////////////////");
		
		Configuration config = Configuration.getInstance();
		String csvFilePath = config.getProperty(CSVConst.DMP_USER_DATA_DIR);
		String csvFileName = config.getProperty(CSVConst.DMP_USER_DATA_FILE_NAME);
		
		String fileAbsolutePath = new StringBuilder().append(csvFilePath).append(File.separator).append(csvFileName).toString();
		File file = new File(fileAbsolutePath);
		String appName = file.getName().split("_")[0];
		System.out.println(appName);
		System.out.println(fileAbsolutePath);
		List<Map<String, String>> keyValpairs = getKeyValPairsFromCSVFile(file);
		int counter = 0;
		for (Map<String, String> map : keyValpairs) {
			for (Entry<String, String> entry : map.entrySet()) {
				String key = entry.getKey();
				String val = entry.getValue();
				System.out.println(
								key + " - " + 
								val + " @ " 
								+ appName
								);
			}
			counter++;
			if (counter == 100) {
				break;
			}
			System.out.println("===========" + counter + "===========");
		}
	}
}
